package cn.yogehaoren.badfox.http.okhttp;


import cn.yogehaoren.badfox.def.BaseBadFox;
import cn.yogehaoren.badfox.http.HttpMethod;
import cn.yogehaoren.badfox.struct.CrawlerModel;
import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.Request;
import okhttp3.RequestBody;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.CollectionUtils;

import java.util.Map;

/**
 */
public class OkHttpRequestGenerator {
    public static Request.Builder getOkHttpRequesBuilder(cn.yogehaoren.badfox.struct.Request request, CrawlerModel crawlerModel){
        BaseBadFox crawler = crawlerModel.getInstance();
        Request.Builder requestBuilder = new Request.Builder();

            requestBuilder.url(request.getUrl());
            requestBuilder.header("User-Agent", crawlerModel.isUseCookie() ? crawlerModel.getCurrentUA() : crawler.getUserAgent())
                    .header("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8")
                    .header("Accept-Language", "zh-CN,zh;q=0.8,en;q=0.6");
            //自定义header
            if (!CollectionUtils.isEmpty(request.getHeader())) {
                for (Map.Entry<String,String> entry:request.getHeader().entrySet()) {
                    requestBuilder.addHeader(entry.getKey(), entry.getValue());
                }
            }
            if (HttpMethod.POST.equals(request.getHttpMethod())) {
                if (StringUtils.isNotBlank(request.getJsonBody())){
                    RequestBody requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"),request.getJsonBody());
                    requestBuilder.post(requestBody);
                }else {
                    FormBody.Builder formBodyBuilder = new FormBody.Builder();
                    if (request.getParams() != null) {
                        for (Map.Entry<String, String> entry : request.getParams().entrySet()) {
                            formBodyBuilder.add(entry.getKey(), entry.getValue());
                        }
                    }
                    requestBuilder.post(formBodyBuilder.build());
                }
            } else {
                String queryStr = "";
                if (request.getParams()!=null&&!request.getParams().isEmpty()){
                    queryStr += "?";
                    for (Map.Entry<String, String> entry : request.getParams().entrySet()) {
                        queryStr= queryStr+entry.getKey()+"="+entry.getValue()+"&";
                    }
                    requestBuilder.url(request.getUrl()+queryStr);
                }
                requestBuilder.get();
            }

        return requestBuilder;
    }
}
